package com.qf.vote.service.impl;

import cn.hutool.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.vote.dao.phoneTokenMapper;
import com.qf.vote.entity.PhoneToken;
import com.qf.vote.entity.Ticket;
import com.qf.vote.service.TicketService;
import com.qf.vote.service.PhoneTokenService;
import com.qf.vote.utils.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yyq
 * @since 2023-02-25
 */
@Service
public class PhoneTokenServiceImpl extends ServiceImpl<phoneTokenMapper, PhoneToken> implements PhoneTokenService {
    @Autowired
    TicketService ticketService;

    /**
     * token颁发接口
     *
     * @param phone
     * @return
     */
    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public String selectToken(@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection") String phone) {
        PhoneToken userPhone = getOne(new QueryWrapper<PhoneToken>().eq("phone", phone));
        if (userPhone == null || "".equals(userPhone)) {
            return "-1";
        } else {
            return userPhone.getToken();
        }
    }

    /**
     * token颁发接口
     *
     * @param phone
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String insertToken(String phone) {
        String token = JWT.create()
                .setPayload("phone", phone)
                .setExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60))
                .setKey(Constants.SECRET.getBytes(StandardCharsets.UTF_8))
                .sign();
        PhoneToken userPhone = new PhoneToken();
        userPhone.setPhone(phone);
        userPhone.setToken(token);
        saveOrUpdate(userPhone, new QueryWrapper<PhoneToken>().eq("phone", phone));
        return token;

    }

    /**
     * 投票接口
     *
     * @param phone
     * @param token
     * @param name
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String voting(String phone, String token, String name) {
        if (token == null || "".equals(token)) {
            return "token无效";
        }
        PhoneToken phoneTokenDb = getOne(new QueryWrapper<PhoneToken>().eq("token", token));
        String tokenDb = phoneTokenDb.getToken();
        if (token == null || "".equals(token)) {
            return "token无效";
        }
        boolean validate = JWT.of(tokenDb).setKey(Constants.SECRET.getBytes(StandardCharsets.UTF_8)).validate(0);
        if (validate) {
            Date date = phoneTokenDb.getVotingdate();
            long votingdate = 0l;
            if (date == null) {
                votingdate = 0l;
            } else {
                votingdate = date.getTime();
            }
            //long newLong = System.currentTimeMillis();
            long newLong = new Date().getTime(); //时间转long
            if ((newLong - votingdate) > 60 * 1000) {
                Ticket ticker = new Ticket();
                ticker.setName(name);
                ticker.setTicket((ticketService.getOne(new QueryWrapper<Ticket>().eq("name", name)).getTicket()) + 1);
                ticketService.saveOrUpdate(ticker, new QueryWrapper<Ticket>().eq("name", name));
                PhoneToken phoneToken1 = new PhoneToken();
                phoneToken1.setVotingdate(new Date());
                saveOrUpdate(phoneToken1, new QueryWrapper<PhoneToken>().eq("phone", phone));
                return "投票成功";
            } else {
                return "一分钟只能投票一次";
            }
        } else {
            return "-1";
        }

    }

    /**
     * 给前端页面推送数据
     *
     * @return
     */
    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public long AllTicket() {
        long count = count();
        return count;
    }
}













